import socket

class Input:
	def __init__(self, owner, command_fragment):
		self.owner = owner
		self.command_fragment = command_fragment		
	def getValue(self):
		return self.owner.process_command(self.command_fragment + '.get\n')

class Output:
	def __init__(self, owner, command_fragment):
		self.owner = owner
		self.command_fragment = command_fragment		
	def getValue(self):
		return self.owner.process_command(self.command_fragment + '.get\n')

	def setValue(self):
		return self.owner.process_command(self.command_fragment + '.set\n')


class Channel:
	def __init__(self, owner, command_fragment):
		self.owner = owner
		self.command_fragment = command_fragment
		self.input = Input(self, command_fragment + '.input')
		self.output = Output(self, command_fragment + '.output');

	def keep(self):
		return self.owner.process_command(self.command_fragment + '.keep\n')

	def keep(self, val):
		return self.owner.process_command(self.command_fragment + '.keep(' + str(val) + ')\n')

	def disable(self):
		return self.owner.process_command(self.command_fragment + '.disable\n')

	def process_command(self, command):
		return self.owner.process_command(command)


class Channels:
	def __init__(self, owner):
		self.owner = owner

	def __getitem__(self, index):
		return Channel(self, 'channel[' + index + ']')

	def process_command(self, command):
		return self.owner.process_command(command)


class ControlLoopTCPConnection:
	def __init__(self):
		self.channel = Channels( self )

	def connect(self, host, port):
		try:
			self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			self.socket.connect((host, port))
		except socket.error, msg:
			pass

	def disconnect():
		self.socket.close()

	def process_command(self, command):
		self.socket.send(command)
		data = self.socket.recv(1024)
		server_response = data
#		server_response = ""
#		while len(data):
#			server_response = server_response + data
#			data = self.socket.recv(1024)
		#process returned data
		rows = data.splitlines()
		if rows[0] == 'ok':
			result = ''
			if len(rows) > 1:
				result = rows[1]
			return result
		elif rows[0] == 'error': #Server returned an error
			error_description = ''
			if len(rows) > 1:
				error_description = rows[1]
			raise ControlLoopError(error_description)
		else: #Can't parse response
			raise ControlLoopError("Can't parse response")

